#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/8/26 14:48
# @Author : way
# @Site :
# @Describe:

from flask import Flask, render_template, request, redirect
from data import *
import json
import datetime
def get_current_month():
    return datetime.datetime.now().strftime('%Y-%m')

def load_json():
    with open('dezhou.json', 'r', encoding='utf-8') as f:
        return json.load(f)

def save_json(data):
    with open('dezhou.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
app = Flask(__name__)

@app.route('/admin', methods=['GET'])
def admin():
    data = load_json()
    def get_page(name):
        try:
            return int(request.args.get(name + '_page', 1))
        except Exception:
            return 1
    page_size = 10
    # counters统计
    employment_count = sum(len(m.get('youths', [])) for m in data.get('employment_detail', {}).get('monthly', []))
    enterprise_count = len(data.get('enterprise_detail', {}).get('districts', []))
    training_count = len(data.get('training_detail', {}).get('monthly', []))
    activity_count = len(data.get('activity_detail', {}).get('monthly', []))
    incubation_count = len(data.get('incubation_detail', {}).get('monthly', []))
    counters = {
        'employment': {'name': '服务就业人数', 'value': employment_count},
        'enterprise': {'name': '服务企业数量', 'value': enterprise_count},
        'training': {'name': '服务培训人数', 'value': training_count},
        'activity': {'name': '组织活动人数', 'value': activity_count},
        'incubation': {'name': '孵化创业项目', 'value': incubation_count}
    }
    # 就业数据处理
    employment_data = []
    for m in data.get('employment_detail', {}).get('monthly', []):
        for y in m.get('youths', []):
            employment_data.append({
                'month': m['month'],
                'name': y['name'],
                'age': y['age'],
                'education': y['education']
            })
    employment_data.sort(key=lambda x: x['month'], reverse=True)
    employment_page = get_page('employment')
    employment_total = len(employment_data)
    employment_data = employment_data[(employment_page-1)*page_size:employment_page*page_size]

    # 企业数据处理
    enterprise_data = data.get('enterprise_detail', {}).get('districts', [])
    enterprise_data.sort(key=lambda x: x['month'], reverse=True)
    enterprise_page = get_page('enterprise')
    enterprise_total = len(enterprise_data)
    enterprise_data = enterprise_data[(enterprise_page-1)*page_size:enterprise_page*page_size]

    # 培训数据处理
    training_data = data.get('training_detail', {}).get('monthly', [])
    training_data.sort(key=lambda x: x['month'], reverse=True)
    training_page = get_page('training')
    training_total = len(training_data)
    training_data = training_data[(training_page-1)*page_size:training_page*page_size]

    # 活动数据处理
    activity_data = data.get('activity_detail', {}).get('monthly', [])
    activity_data.sort(key=lambda x: x['month'], reverse=True)
    activity_page = get_page('activity')
    activity_total = len(activity_data)
    activity_data = activity_data[(activity_page-1)*page_size:activity_page*page_size]

    # 孵化数据处理
    incubation_data = data.get('incubation_detail', {}).get('monthly', [])
    incubation_data.sort(key=lambda x: x['month'], reverse=True)
    incubation_page = get_page('incubation')
    incubation_total = len(incubation_data)
    incubation_data = incubation_data[(incubation_page-1)*page_size:incubation_page*page_size]

    return render_template('admin.html',
        current_month=get_current_month(),
        counters=counters,
        employment_data=employment_data,
        employment_page=employment_page,
        employment_total=employment_total,
        enterprise_data=enterprise_data,
        enterprise_page=enterprise_page,
        enterprise_total=enterprise_total,
        training_data=training_data,
        training_page=training_page,
        training_total=training_total,
        activity_data=activity_data,
        activity_page=activity_page,
        activity_total=activity_total,
        incubation_data=incubation_data,
        incubation_page=incubation_page,
        incubation_total=incubation_total,
        page_size=page_size
    )
@app.route('/add_employment', methods=['POST'])
def add_employment():
    month = request.form.get('month') or get_current_month()
    name = request.form.get('name')
    age = int(request.form.get('age'))
    education = request.form.get('education')
    data = load_json()
    # 找到对应月份，没有则新建
    monthly = data.setdefault('employment_detail', {}).setdefault('monthly', [])
    for m in monthly:
        if m['month'] == month:
            m['youths'].append({'name': name, 'age': age, 'education': education})
            break
    else:
        monthly.append({'month': month, 'youths': [{'name': name, 'age': age, 'education': education}]})
    # 更新学历统计
    ec = data['employment_detail'].setdefault('education_count', {})
    ec[education] = ec.get(education, 0) + 1
    save_json(data)
    return redirect('/admin')
@app.route('/add_enterprise', methods=['POST'])
def add_enterprise():
    month = request.form.get('month') or get_current_month()
    name = request.form.get('name')
    district = request.form.get('district')
    job = request.form.get('job')
    data = load_json()
    districts = data.setdefault('enterprise_detail', {}).setdefault('districts', [])
    districts.append({'month': month, 'name': name, 'district': district, 'job': job})
    save_json(data)
    return redirect('/admin')
@app.route('/add_training', methods=['POST'])
def add_training():
    month = request.form.get('month') or get_current_month()
    name = request.form.get('name')
    age = int(request.form.get('age'))
    education = request.form.get('education')
    content = request.form.get('content')
    data = load_json()
    monthly = data.setdefault('training_detail', {}).setdefault('monthly', [])
    monthly.append({'month': month, 'name': name, 'age': age, 'education': education, 'content': content})
    save_json(data)
    return redirect('/admin')
@app.route('/add_activity', methods=['POST'])
def add_activity():
    month = request.form.get('month') or get_current_month()
    name = request.form.get('name')
    count = int(request.form.get('count'))
    data = load_json()
    monthly = data.setdefault('activity_detail', {}).setdefault('monthly', [])
    monthly.append({'month': month, 'name': name, 'count': count})
    save_json(data)
    return redirect('/admin')
@app.route('/add_incubation', methods=['POST'])
def add_incubation():
    month = request.form.get('month') or get_current_month()
    name = request.form.get('name')
    industry = request.form.get('industry')
    data = load_json()
    monthly = data.setdefault('incubation_detail', {}).setdefault('monthly', [])
    monthly.append({'month': month, 'name': name, 'industry': industry})
    save_json(data)
    return redirect('/admin')


@app.route('/')
def index():
    data = SourceData()
    return render_template('index.html', form=data, title=data.title)

@app.route('/corp')
def corp():
    data = CorpData()
    return render_template('index.html', form=data, title=data.title)

@app.route('/job')
def job():
    data = JobData()
    return render_template('index.html', form=data, title=data.title)

@app.route('/dezhou')
def dezhou():
    data = DezhouData()
    return render_template('index.html', form=data, title=data.title)


if __name__ == "__main__":
    print('已注册的路由:')
    for rule in app.url_map.iter_rules():
        print(rule)
    app.run(host='127.0.0.1', port=5000, debug=True)
